<template>
  <el-button :loading="sendingCaptcha" :disabled="disableGetCaptcha" @click="getCaptcha">{{getCaptchaButton}}
  </el-button>
</template>

<script>
import { getRegisterEmailCaptcha } from "@/api/admin/user"
import { getUserRegisterEmailCaptcha,getFindPasswordEmailCaptcha } from "@/api/front/user"

export default {
  data() {
    return {
      sendingCaptcha: false,//加载发送验证码
      disableGetCaptcha: false,//禁用发送验证码
      getCaptchaButton: '获取验证码',//发送验证码按钮信息
      timer: null,//定时器
    }
  },
  props: {
    email: {
      type: String,
      required: true,
      default: ''
    },
    reUtype: {
      type: String,
      required: true,
      default: 'admin'
    }
  },
  methods: {
    //获取验证码
    getCaptcha() {
      if (this.email) {
        this.sendingCaptcha = true
        this.getCaptchaButton = '正在发送'
        //发送验证码
        if (this.reUtype == 'admin') {
          getRegisterEmailCaptcha({ email: this.email }, (res) => {
            this.handleSendCaptcha(res)
          }, true)
        }
        else if (this.reUtype == 'user') {
          getUserRegisterEmailCaptcha({ email: this.email }, (res) => {
            this.handleSendCaptcha(res)
          }, true)
        }
        else if(this.reUtype == "findUserPassword"){
          getFindPasswordEmailCaptcha({email:this.email}, (res) => {
            this.handleSendCaptcha(res)
          },true)
        }
        else {
          this.$message({
            message: '错误的用户类型',
            type: 'warning'
          })
        }
      }
      else {
        this.$message({
          message: '请填写邮箱',
          type: 'warning'
        })
      }
    },
    handleSendCaptcha(res) {
      this.sendingCaptcha = false
      if (res.code == 200) {
        let time = 120
        let that = this
        this.disableGetCaptcha = true;
        this.timer = setInterval(() => {
          if (time--) {
            that.getCaptchaButton = `${time}s 后重新发送`
          }
          else {
            that.getCaptchaButton = "获取验证码"
            that.disableGetCaptcha = false;
            clearInterval(that.timer)
          }
        }, 1000);
        this.$emit("setCpatchaMD5", res.captcha)
      }
      else {
        this.getCaptchaButton = "获取验证码"
      }
    }
  },
  beforeDestroy() {
    if (this.timer != null) {
      clearInterval(this.timer)
    }
  }
}
</script>